<template>
  <el-dialog v-model="isShowLoginDialog" width="370px" align-center class="loginDialog" @closed="onClose">
    <template #header="{ close, titleId, titleClass }">
      <div v-if="isShowQrCode">
        <h4 :id="titleId" :class="titleClass">二维码登陆</h4>
      </div>
      <div v-if="!isShowQrCode" class="my-header">
        <img @click="onShowQrCode" src="/src/assets/image/qrCode.svg">
        <h4 :id="titleId" :class="titleClass" class="title-text">账号登陆</h4>
      </div>
    </template>
    <!-- 二维码登陆 -->
    <div v-if="isShowQrCode" class="qrcode-login" >
      <!-- 二维码 -->
      <img v-if="qrCode.url" :src="qrCode.url">
      <!-- 二维码过期 -->
      <div v-if="isExpire && !isScan" :style="`width: ${qrCode.width}px;height: ${qrCode.height}px;`" class="qrcode-expire-mask">
        <el-result icon="error" title="二维码已过期,请重新获取">
          <template #extra>
            <el-button icon="RefreshRight" @click="onShowQrCode">刷新二维码</el-button>
          </template>
        </el-result>
      </div>
      <!-- 二维码已扫描且已绑定账号 -->
      <div v-if="isScan && isBind" :style="`width: ${qrCode.width}px;height: ${qrCode.height}px;`" class="qrcode-expire-mask">
        <el-result icon="success" title="扫码成功,正在登陆中..."></el-result>
      </div>
      <!-- 二维码已扫描且未绑定账号 -->
      <div v-if="isScan && !isBind" :style="`width: ${qrCode.width}px;height: ${qrCode.height}px;`" class="qrcode-expire-mask">
        <el-result icon="warning" title="该微信暂未绑定账号" sub-title="请用账号密码登陆后,在头像旁的下拉菜单中选择: 微信账号绑定"></el-result>
      </div>
      <!-- 文字提示 -->
      <span v-if="!isExpire && !isScan && !isLoading" class="qrcode-text">请使用微信扫一扫~</span>
      <span v-if="!isExpire && !isScan && !isLoading" class="qrcode-text">二维码将在{{ qrCode.expireSeconds }}秒后过期</span>
    </div>
    <!-- 账号登陆 -->
    <div v-if="!isShowQrCode" class="password-login" v-loading="isLoading">
      <el-form :model="user" label-width="30px" :rules="rule" ref="formRef" hide-required-asterisk>
        <el-form-item prop="accountNumber">
          <template #label>
            <el-icon :size="18"><UserFilled /></el-icon>
          </template>
          <el-input v-model="user.accountNumber"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <template #label>
            <el-icon :size="18"><Briefcase /></el-icon>
          </template>
          <el-input v-model="user.password" show-password></el-input>
        </el-form-item>
        <el-form-item prop="role" class="last-form-item">
          <el-radio-group v-model="user.role">
            <el-radio :label="0" size="large">学生</el-radio>
            <el-radio :label="1" size="large">教师</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <section>
        <span type="text" @click="isShowDrawer = true">忘记密码</span>
      </section>

      <button @click="login">
        <svg viewBox="25 25 50 50" v-if="isClickBtn">
          <circle cx="50" cy="50" r="20"></circle>
        </svg>
        <span v-else>登录</span>
      </button>

      <article id="tips">
        <div>温馨提示:</div>
        老师账号为工号，学生为学号，初始密码为
        <span>身份证后六位</span>。
      </article>
    </div>
  </el-dialog>

  <!-- 修改密码的抽屉 -->
  <forget-password :is-show="isShowDrawer" @on-closed="onDrawerClosed"></forget-password>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { APIData, UserLogin } from '../../type';
import { ElMessage } from 'element-plus';
import ForgetPassword from './ForgetPassword.vue';
import { useRuleUtils } from '../../utils/validate';
import { useAPI } from '../../request/api';

let timeCountdownTimer = -1;
let cycleLoginTimer = -1;
let qrCodeTimeStamp = '';
const formRef = ref();
const ruleUtils = useRuleUtils();
const api = useAPI();
const isShowQrCode = ref<boolean>(false);
const isExpire = ref<boolean>(false);
const isScan = ref<boolean>(false);
const isBind = ref<boolean>(true);
const isLoading = ref<boolean>(false);
const qrCode = ref({ url: '',expireSeconds: 0,width: 0,height: 0})
const isClickBtn = ref<boolean>(false);
const isShowDrawer = ref<boolean>(false);
const isShowLoginDialog = ref<boolean>();
const user = reactive<UserLogin>({
  accountNumber: '',
  password: '',
  role: 0
});


const onDrawerClosed = () => {
  isShowDrawer.value = false;
};

const emit = defineEmits(['onLoginBtnClick','onQrCodeLogin']);
const login = () => {
  isClickBtn.value = !isClickBtn.value;
  if (isClickBtn.value) {
    const formEl = formRef.value;
    if (!formEl) return;
    formEl.validate(async (valid: any) => {
      if (valid) emit('onLoginBtnClick', user);
    });
  }
};

// const onShowQrCode = () => {
//   buildQrCode();
// }

const onShowQrCode = async () => {
  isLoading.value = true;
  
  qrCodeTimeStamp = String(new Date().getTime());
  const res: APIData = await api.getQrCode({ qrCodeParams: qrCodeTimeStamp});
  if (res.code === 200) {
    qrCode.value = {
      url: `data:image/jpeg;base64,${res.data.qrCodeBase64}`,
      // url: '/src/assets/image/testCode.png',
      // expireSeconds: 3600,
      expireSeconds: res.data.expireSeconds,
      width: res.data.width,
      height: res.data.height
    }
    isShowQrCode.value = true;
    isLoading.value = false;
    isExpire.value = false;
    isScan.value = false;

    timeCountdown();
    cycleQueryToLogin();
  }
  else ElMessage.error('网络不稳定，请重新生成登陆二维码');
}

const timeCountdown = async () => {
  timeCountdownTimer = setInterval(() => {
    if (qrCode.value.expireSeconds > 1) qrCode.value.expireSeconds--;
    else {
      if(timeCountdownTimer != -1) clearInterval(timeCountdownTimer);
      if(cycleLoginTimer != -1) clearInterval(cycleLoginTimer);
      isExpire.value = true; 
      //也要结束轮询计时器
    }
  }, 1000);
}

const cycleQueryToLogin = () => {
  cycleLoginTimer = setInterval(async () => {
    const res:APIData = await api.loginByQrCode({ timeStamp: qrCodeTimeStamp});
    if (res.code == 200 && res.data) {
      isScan.value = true;
      if(cycleLoginTimer != -1) clearInterval(cycleLoginTimer);
      setTimeout(() => emit('onQrCodeLogin', res), 500);
    }else if(res.code == 200 && res.message == '该微信的用户暂未绑定系统账号') {
      isScan.value = true;
      isBind.value = false;
      if(cycleLoginTimer != -1) clearInterval(cycleLoginTimer);
    }
  }, 2000);
}

const onClose = () => {
  // if(!isShowQrCode) 
  console.log('出发了');
  
  if(formRef.value) formRef.value.clearValidate();
  isShowQrCode.value = false;
  isExpire.value = false;
  isScan.value = false;
  isBind.value = true;
  isLoading.value = false;
  if(timeCountdownTimer != -1) clearInterval(timeCountdownTimer);
  if(cycleLoginTimer != -1) clearInterval(cycleLoginTimer);
}

const rule = {
  accountNumber: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ validator: ruleUtils.password, trigger: 'blur' }],
};


defineExpose({ isClickBtn,isShowLoginDialog});
</script>

<style lang="scss">
.loginDialog {
  background-color: #fff !important;
}
</style>

<style lang="scss" scoped>
// 账号登录的样式  ---------------
.password-login {
  section {
    text-align: end;
    height: 30px;

    span {
      color: #606266;
      padding: 6px;
      cursor: pointer;
    }
  }

  .last-form-item {
    margin-bottom: 0;
  }

  //输入框前的图标水平垂直居中
  :deep(.el-form-item__label) {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  :deep(.el-input__wrapper) {
    background-color: #fff !important;
  }

  :deep(.el-form-item__label),
  :deep(.el-input__inner) {
    color: black !important;
  }

  button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 50px;
    border: none;
    color: whitesmoke;
    margin-top: 10px;
    border-radius: 4px;
    letter-spacing: 8px;
    font-size: 16px;
    transition: all 0.5s ease;
    background-image: linear-gradient(30deg, #0061ce, #00b5fb);

    svg {
      width: 20px;
      transform-origin: center;
      animation: rotate 2s linear infinite;
    }

    circle {
      fill: none;
      stroke: #fff;
      stroke-width: 2;
      stroke-dasharray: 1, 200;
      stroke-dashoffset: 0;
      stroke-linecap: round;
      animation: dash 1.5s ease-in-out infinite;
    }

    @keyframes rotate {
      100% {
        transform: rotate(360deg);
      }
    }

    @keyframes dash {
      0% {
        stroke-dasharray: 1, 200;
        stroke-dashoffset: 0;
      }

      50% {
        stroke-dasharray: 90, 200;
        stroke-dashoffset: -35px;
      }

      100% {
        stroke-dashoffset: -125px;
      }
    }
  }

  button:hover {
    cursor: pointer;
    transition: all 0.3s ease;
    transform: translateY(-2px);
    box-shadow: 0 8px 36px 0px #0061ce;
    // box-shadow: 0 4px 20px 12px rgba(0, 0, 0, 0.1);
  }

  article {
    color: black;

    div {
      margin: 20px 0 10px 0;
      font-size: 18px;
      font-weight: bold;
    }

    span {
      font-weight: bold;
    }
  }
}

.my-header {
  position: relative;
  user-select: none;

  img {
    position: absolute;
    top: -20px;
    left: -20px;
    transform: rotateY(0.5turn); //镜像翻转,沿Y轴反转180度
    cursor: pointer;
  }

  .title-text {
    margin-left: 35px;
    cursor: default;
  }
}

// 二维码登录的样式  ---------------
.qrcode-login {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  // border: 1px solid red;
  // .back-btn {
  //   border: 1px solid green;
  //   padding: 8px;
  // }
  .qrcode-text {
    margin-top: 8px;
    // border: 1px solid green;
  }
  .qrcode-expire-mask {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    // top: 10px;
    // left: 10px;
    background-color: #fffffff5;
    // border: 1px solid #95beec;
  }
}
</style>
